define(['knockout',
    'platform.common',
    'bootbox',
    'knockout-bsTable',
    'knockout-component',
    'sco.msg',
    'anychart-base', 'anychart-core', 'anychart-pareto',
    'anychart-theme-lightblue'], function (ko, platform) {
    var rest = {
        remove: function (id) {
            var param = {};
            param.record_id = id;
            platform.servicebreakAsync("~/rest/record/removePowerDataByRecordId", param, 'post').done(function (response) {
                if (response instanceof Object && response.meta.success) {
                    platform.showOperTip('DELSUC');
                    vm.tableViewModel.refresh();
                } else {
                    platform.showErrorTip(response.meta.message);
                }
            }).fail(function (response) {

            });
        },
        getCalLog: function (id) {
            var param = {};
            param.record_id = id;
            return platform.servicebreak('~/rest/record/getCalLogByRecordId', param).responseJSON;
        },
        exportXlxs: function (id, name) {
            var param = {};
            param.fileName = name;
            param.sheets = [];
            param.sheets.push({sheetname: '台区标杆线损', filter: {method: 'getTranPowerByRecordId', args: {record_id: id}}});
            param.sheets.push({sheetname: '线段分段线损明细', filter: {method: 'getSegPowerByRecord', args: {record_id: id}}});
            platform.exportExcel(param);
        }
    };

    var kbTable = require('knockout-bsTable');
    var bootbox = require('bootbox');
    // var dataSetA, dataSetB, dataSetC, chartData, currentChart, rateChart;

    var tgOpts = platform.servicebreak("~/rest/tg/getTgDict").responseJSON.responseObject;

    var VM = function () {
            self = this;
            self.tgOpts = ko.computed(function () {
                return tgOpts;
            });
            self.fixedTgId = ko.observable();
            self.columns = [{checkbox: true, align: 'center', width: 30}, {
                field: 'display_order', title: '序号',
                formatter: function (value, row, index) {
                    var options = self.tableViewModel.getOptions();
                    var indexPageNum = parseInt(options.pageNumber);
                    var indexPageSize = parseInt(options.pageSize);
                    return ((indexPageNum - 1) * indexPageSize)
                        + (index + 1);
                },
                width: 35, align: 'center'
            }, {
                field: 'record_id', title: '主键标识', visible: false
            }, {
                field: 'tg_no', title: '台区编号'
            }, {
                field: 'tg_name', title: '台区名称'
            }, {
                field: 'tran_no', title: '配变编号'
            }, {
                field: 'tran_name', title: '配变名称'
            }, {
                field: 'section_date', title: '断面日期', align: 'center'
            }, {
                field: 'power_input', title: '输入电量(kWh)', align: 'right'
            }, {
                field: 'power_output', title: '售电量合计(kWh)', align: 'right'
            }, {
                field: 'power_loss', title: '损失电量(kWh)', align: 'right'
            }, {
                field: 'act_loss_rate', title: '实际线损率(%)', align: 'right'
            }, {
                field: 'power_rate', title: '标杆线损率(%)', align: 'right'
            }, {
                field: 'cal_date', title: '计算时间', align: 'center'
            }, {
                field: 'tran_id', visible: false
            }];
            self.tableViewModel = new kbTable.bootstrapTableViewModel({
                url: platform.mapUrl('~/rest/record/getTranPowerByPage'),
                columns: self.columns,
                toolbar: '#toolbar',
                queryParams: function (params) {
                    return {
                        pageNumber: params.offset / params.limit + 1,
                        pageSize: params.limit,
                        tg_id: self.fixedTgId()
                    };
                }
            });

            self.detailDlgVisible = ko.observable(false);
            self.detailsViewModel = {
                title: ko.observable(''),
                recordId: ko.observable(),
                detailsTable: new kbTable.bootstrapTableViewModel({
                    url: platform.mapUrl('~/rest/record/getSegPowerInPage'),
                    columns: [{checkbox: true, align: 'center', width: 30}, {
                        field: 'display_order', title: '序号',
                        formatter: function (value, row, index) {
                            var options = self.detailsViewModel.detailsTable.getOptions();
                            var indexPageNum = parseInt(options.pageNumber);
                            var indexPageSize = parseInt(options.pageSize);
                            return ((indexPageNum - 1) * indexPageSize)
                                + (index + 1);
                        }, width: 35, align: 'center'
                    }, {
                        field: 'seg_id', title: '分段标识', visible: false
                    }, {
                        field: 'seg_no', title: '分段编号'
                    }, {
                        field: 'rate_loss_seg', title: '线损率(%)', align: 'right'
                    }, {
                        field: 'power_input', title: '输入电量(kWh)', align: 'right'
                    }, {
                        field: 'power_output', title: '输出电量(kWh)', align: 'right'
                    }, {
                        field: 'power_loss', title: '损失电量(kWh)', align: 'right'
                    }, {
                        field: 'power_rest', title: '末端用户电量(kWh)', align: 'right'
                    }, {
                        field: 'unit_resistance', title: '分段电阻(Ω)', align: 'right'
                    }, {
                        field: 'eq_resistance', title: '等值电阻(Ω)', align: 'right'
                    }], queryParams: function (params) {
                        return {
                            pageNumber: params.offset / params.limit + 1,
                            pageSize: params.limit,
                            record_id: self.detailsViewModel.recordId()
                        };
                    }, showRefresh: false, showColumns: false, pageSize: 5, height: 275
                }), showForm: function (id, tranId, name) {
                    this.recordId(id);
                    this.detailsTable.refresh({record_id: id});
                    this.title('【' + name + '】台区明细数据查看');
                    var param = {};
                    param.tran_id = tranId;
                    param.record_id = id;
                    platform.servicebreakAsync('~/rest/tran/getTranCurrentCurse', param).done(function (response) {
                            var dataSetA = null, dataSetB = null, dataSetC = null, chartData = null, currentChart = null,
                                rateChart = null;
                            if (response instanceof Object) {
                                var seriesData_1, seriesData_2, seriesData_3;

                                $('#resultContainer').empty();
                                $('#currentCurse').empty();

                                anychart.onDocumentReady(function () {

                                    var k1 = response.result.caseK1;
                                    var k2 = response.result.caseK2;
                                    var k3 = response.result.caseK3;

                                    chartData = {
                                        title: '三相不平衡时标杆线损',
                                        header: ['#', '三相不平衡度', '损失电量', '损失率'],
                                        rows: [
                                            ['一重两轻', k1.kValue, k1.lossPower, k1.lossRate],
                                            ['一重一轻一平均', k2.kValue, k2.lossPower, k2.lossRate],
                                            ['一轻两重', k3.kValue, k3.lossPower, k3.lossRate]
                                        ]
                                    };

                                    rateChart = anychart.column();
                                    rateChart.data(chartData);
                                    rateChart.animation(true);
                                    rateChart.interactivity().hoverMode('single');

                                    rateChart.xAxis().stroke(null);
                                    rateChart.yAxis().title('示值');
                                    rateChart.yAxis().labels().format('{%Value}.');

                                    var zeroMarker = rateChart.lineMarker(0);
                                    zeroMarker.stroke('#ddd');
                                    zeroMarker.scale(rateChart.yScale());
                                    zeroMarker.value(0);
                                    rateChart.labels(true);
                                    rateChart.tooltip().title(false).separator(false);
                                    rateChart.legend().enabled(true).fontSize(13).padding([0, 0, 20, 0]);
                                    rateChart.xGrid().stroke('#ddd').drawLastLine(false);
                                    rateChart.barsPadding(0.1).barGroupsPadding(0.9);
                                    rateChart.container('resultContainer');
                                    rateChart.draw();

                                    var curse = response.curse;
                                    $.each(curse, function (index, data) {
                                        if (data.phase == '01') {
                                            seriesData_1 = data.values;
                                        } else if (data.phase == '02') {
                                            seriesData_2 = data.values;
                                        } else if (data.phase == '03') {
                                            seriesData_3 = data.values;
                                        }
                                    });
                                    dataSetA = anychart.data.set();
                                    dataSetB = anychart.data.set();
                                    dataSetC = anychart.data.set();

                                    dataSetA.data(seriesData_1);
                                    dataSetB.data(seriesData_2);
                                    dataSetC.data(seriesData_3);

                                    currentChart = anychart.line();
                                    currentChart.padding([10, 20, 5, 20]);
                                    currentChart.animation(true);
                                    currentChart.crosshair(true);
                                    currentChart.title('24小时电流曲线图');
                                    currentChart.yAxis(0).title('电流值(A)');

                                    var seriesA, seriesB, seriesC;
                                    seriesA = currentChart.line(dataSetA.mapAs({x: 'time_set'}));
                                    seriesA.name('A相电流');
                                    seriesA.labels().enabled(true).anchor('left-bottom').padding(5);
                                    seriesA.markers(true);
                                    seriesB = currentChart.line(dataSetB.mapAs({x: 'time_set'}));
                                    seriesB.name('B相电流');
                                    seriesB.labels().enabled(true).anchor('left-bottom').padding(5);
                                    seriesB.markers(true);
                                    seriesC = currentChart.line(dataSetC.mapAs({x: 'time_set'}));
                                    seriesC.name('C相电流');
                                    seriesC.labels().enabled(true).anchor('left-bottom').padding(5);
                                    seriesC.markers(true);
                                    currentChart.legend().enabled(true).fontSize(13).padding([0, 0, 20, 0]);
                                    currentChart.container('currentCurse');
                                    currentChart.draw();
                                });
                            }
                        }
                    );

                    self.detailDlgVisible(true);
                    $('#detailDlg').toggleClass('hide');
                },
                close: function () {
                    $('#resultContainer').empty();
                    $('#currentCurse').empty();
                    self.detailDlgVisible(false);
                    $('#detailDlg').toggleClass('hide');
                }
            }
            ;

            self.calLogDlgVisible = ko.observable(false);
            self.calLogViewModel = {
                title: ko.observable(),
                processMsg: ko.observable(),
                showForm: function (id) {
                    debugger;
                    this.title('计算日志');
                    var msg = rest.getCalLog(id);
                    this.processMsg(msg.responseObject);

                    self.calLogDlgVisible(true);
                    $('#callLogDlg').toggleClass('hide');
                }, close: function () {
                    self.calLogDlgVisible(false);
                    this.processMsg('');
                    $('#calLog').text('');
                    $('#callLogDlg').toggleClass('hide');
                }
            };

            /**
             * toolbar function
             */
            self.fnRemove = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {
                    bootbox.confirm({
                        title: '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
                        size: 'small',
                        message: '确认是否删除?',
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success btn-sm'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default btn-sm'
                            }
                        },
                        callback: function (response) {
                            if (response) {
                                var id = selections[0].record_id;
                                rest.remove(id);
                            }
                        }
                    });
                } else {
                    platform.showTip('remove');

                }
            };
            self.fnViewDetails = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {
                    var id = selections[0].record_id;
                    var tranId = selections[0].tran_id;
                    var name = selections[0].tg_name;
                    self.detailsViewModel.showForm(id, tranId, name);
                } else {
                    platform.showTip('VIEW');
                }
            };
            self.fnViewLog = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {
                    var id = selections[0].record_id;
                    self.calLogViewModel.showForm(id);
                } else {
                    platform.showTip('VIEW');
                }
            };
            self.fnExport = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length === 1) {
                    var recordId = selections[0].record_id;
                    var tgName = selections[0].tg_name;
                    var sectionDate = selections[0].section_date;
                    var filename = tgName + '-[' + sectionDate + ']标杆线损';
                    rest.exportXlxs(recordId, filename);
                } else {
                    platform.showTip('EXPORTEXCELL');
                }
            };
            self.fnSearch = function () {
                var param = {};
                param.tg_id = self.fixedTgId();
                self.tableViewModel.refresh(param);
            };
        }
    ;
    var vm = new VM();
    return vm;
})
;